package cn.wolfcode.cms.util;

//统一异常处理切面

import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

//表示controller功能增强注解
@ControllerAdvice   //date
public class ExceptionHandlerAdvice {

    //表示controller抛异常之后,统一到这个方法处理
    //如果带有参数,表示仅仅处理指定的异常类型
    //此处仅仅处理没有权限异常
    @ExceptionHandler(AuthorizationException.class)
    public void handleException(HandlerMethod method, HttpServletResponse response)
            throws IOException {

        //此处写处理无权限异常
        //easyui操作提示没有权限分2种, 一种ajax方式, 一种页面跳转方式
        //如何区分是ajax请求还是页面请求?
        //根据请求方法中是否贴有ResponseBody而决定, ajax请求都贴有该标签

        //获取当前请求方法上面的ResponseBody注解
        ResponseBody ann = method.getMethodAnnotation(ResponseBody.class);
        if(ann != null){
            //当前方式ajax请求
            //JSONResult--json
            //{success:true, msg:xxx, total:0, rows:[]}
            response.setContentType("text/json;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.write("{\"success\":false,\"msg\":\"无操作权限\", \"total\":0, \"rows\":[]}");
            writer.flush();
            writer.close();

        }else{
            //页面请求
            response.sendRedirect("/nopermission.jsp");
        }

    }

    /*@ExceptionHandler(RuntimeException.class)
    public void handleException2(HandlerMethod method, HttpServletResponse response, Exception e)
            throws IOException {
        response.setContentType("text/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"msg\":\"xxxxx\"}");
        writer.flush();
        writer.close();
    }*/

}
